/* * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.grandcentrix.tray.util;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

public class PreferencesHelper {
    private static final String EMPTY = "";
    private static final String TAG = PreferencesHelper.class.getSimpleName();

    private static PreferencesHelper instance = new PreferencesHelper();

    private final int INITIAL = 0;

    private boolean isInit;
    private static Preferences preferences;

    private PreferencesHelper() {
    }

    public void init(Context context, String sharePrefName) {
        if (this.isInit) {
            LogUtil.warn(TAG, "PreferencesHelper is already inited");
            return;
        }
        this.isInit = true;
        this.preferences = new DatabaseHelper(context).getPreferences(sharePrefName);
    }

    public static PreferencesHelper getInstance() {
        return instance;
    }

    public void putString(String key, String value) {
        if (!this.isInit) {
            return;
        }
        this.preferences.putString(key, value);
        this.preferences.flushSync();
    }

    public String getString(String key) {
        if (this.isInit) {
            return preferences.getString(key, EMPTY);
        }
        LogUtil.debug(TAG, "PreferencesHelper is not inited");
        return EMPTY;
    }

    public void putInt(String key, int value) {
        if (!this.isInit) {
            return;
        }
        this.preferences.putInt(key, value);
        this.preferences.flushSync();
    }

    public int getInt(String key) {
        if (this.isInit) {
            return preferences.getInt(key, INITIAL);
        }
        LogUtil.debug(TAG, "PreferencesHelper is not initiated");
        return INITIAL;
    }

    public void registerObserver(Preferences.PreferencesObserver mSharedPrefsListener) {
        preferences.registerObserver(mSharedPrefsListener);
    }

    public void unregisterObserver(Preferences.PreferencesObserver mSharedPrefsListener) {
        preferences.unregisterObserver(mSharedPrefsListener);
    }
}